package com.erps.CommonUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Config {
	public static String RootDir = "";
	private static String cMachineID = "";

	public static String getRootDir() {
		return RootDir;
	}

	public static void setRootDir(String cRootDir) {
		RootDir = cRootDir;
	}

	public static String getMachineID() {
		if (cMachineID.trim().length() == 0) {
			try {
				cMachineID = ReadString("HOSTID", "00");
			} catch (Exception e) {
				cMachineID = "00";
			}
		}
		return cMachineID;
	}

	public static String readConfigStr(String cFileName, String KeyName, String DefValue) {
		InputStream fis = (new Config()).getClass().getResourceAsStream("/" + cFileName);
		Properties prop = new Properties();
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (prop.get(KeyName) != null)
			return prop.getProperty(KeyName);
		else
			return DefValue;
	}

	public static Integer readConfigInt(String cFileName, String KeyName, int iValue) {
		String cv = readConfigStr(cFileName, KeyName, String.valueOf(iValue));
		try {
			return Integer.parseInt(cv);
		} catch (Exception ex) {
			return iValue;
		}
	}

	public static String ReadString(String KeyName, String DefValue) {
		InputStream fis = (new Config()).getClass().getResourceAsStream("/config.properties");
		Properties prop = new Properties();
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (prop.get(KeyName) != null)
			return prop.getProperty(KeyName);
		else
			return DefValue;

	}

	public static Integer ReadInt(String KeyName, int iValue) {
		String cv = ReadString(KeyName, String.valueOf(iValue));
		try {
			return Integer.parseInt(cv);
		} catch (Exception ex) {
			return iValue;
		}
	}

	public static boolean WriteString(String KeyName, String KeyValue) {
		InputStream fis = ClassLoader.getSystemResourceAsStream("/config.properties");
		Properties prop = new Properties();
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			prop.setProperty(KeyName, KeyValue);
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
}
